package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.tanhua.domain.db.User;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.server.utils.GetRequestJsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class FreezeLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference
    private UserApi userApi;

    /**
     * 拦截登录
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //封装request
        MyHttpServletRequestWrapper myWrapper = new MyHttpServletRequestWrapper(request);
        //拦截登录
        JSONObject json = GetRequestJsonUtil.getRequestJsonObject(request);
        String phone = json.getString("phone");
        User user = userApi.findByMobile(phone);
        if (user == null) {
            return true;
        }
        String s = redisTemplate.opsForValue().get("FREEZE_TYPE_" + user.getId());
        if ("1".equals(s)) {
            response.setStatus(500);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            JSONObject res = new JSONObject();
            res.put("errCode", "0096");
            res.put("errMessage", "账号被封禁");
            out = response.getWriter();
            out.append(res.toString());
            return false;
        }
        return true;
    }
}
